﻿using Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.DataCollection.Model;
using ZR.DataCollection.OperationCore.AbstractFactory;
using ZR.DataCollection.OperationCore.OperationEnum;
using ZR.DataCollection.OperationCore.OperationHelper;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;

namespace ZR.DataCollection.OperationCore.OperationMode
{
    /// <summary>
    /// 检测请求处理
    /// </summary>
    public sealed class Detection : OperationInfoBase
    {
        public override event Action<string> Event_Notification;

        private readonly ITestResultService _testResultService = App.GetRequiredService<ITestResultService>();
        private readonly IToleranceCheckInfoService _toleranceCheckInfoService = App.GetRequiredService<IToleranceCheckInfoService>();
        private readonly IWorkstationConfigService _workstationConfigService = App.GetRequiredService<IWorkstationConfigService>();
        private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private bool collectStatus = true;

        public Detection(int operationType, string stationType) : base(operationType, stationType)
        {
        }

        public override void WorkDetail(ImpParameter imp)
        {
            DataDock? dataDock = imp.objectParam as DataDock;
            var keyValuePairs = CurrentCruxPoint(dataDock.LineCode, dataDock.ProductType, dataDock.ItemNo);
            SpotHandle(imp, keyValuePairs);
        }

        public override void SpotHandle(ImpParameter parameter, Dictionary<int, List<OperationPointConfig>> SpotGroup)
        {
            try
            {
                foreach (var SpotInfo in SpotGroup)
                {
                    switch (SpotInfo.Key)
                    {
                        case (int)DataOperateEnum.Read:
                            ReadFunction(parameter, SpotInfo.Value);
                            break;

                        case (int)DataOperateEnum.Write:
                            SpotInfo.Value.ForEach(x =>
                            {
                                if (!collectStatus && x.ItemWriteValue.Equals("2"))
                                {
                                    parameter.PLCDetail.WriteValue(x.ItemNo, x.ItemWriteValue);
                                    return;
                                }
                                parameter.PLCDetail.WriteValue(x.ItemNo, x.ItemWriteValue);
                            });
                            break;

                        case (int)DataOperateEnum.Verify:
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("数据保存Error", ex);
            }
        }

        private void ReadFunction(ImpParameter parameter, List<OperationPointConfig> operationPointList)
        {
            DataDock? dataDock = parameter.objectParam as DataDock;
            bool tve = _workstationConfigService.QueryInfo(dataDock.LineCode, dataDock.StationCode).ToleranceVerificationEnabled.Equals(1);
            for (int i = 0; i < operationPointList.Count - 1; i = i + 2)
            {
                string value1 = (string)parameter.PLCDetail.ReadAddress(operationPointList[i].ItemAddress);//值[i]
                string value2 = (string)parameter.PLCDetail.ReadAddress(operationPointList[i + 2].ItemAddress);//结果[i+2]
                logger.Info("检测请求", dataDock.ProductCode + "值：" + value1);
                TestResult testResult = new TestResult();
                testResult.WorkResult = value2 == "1" ? "OK" : "NG";
                if (tve)
                {
                    List<ToleranceCheckInfo> checkList = _toleranceCheckInfoService.QueryInfo(dataDock.LineCode, dataDock.StationCode, operationPointList[i].ItemNo);
                    if (!checkList.Any())
                    {
                        logger.Error("公差参数", "checkList为空");
                        collectStatus = false;
                        return;
                    }
                    ToleranceCheckInfo? checkInfo = checkList.Find(f => f.UpLimitValue >= Convert.ToDecimal(value1) && f.DownLimitValue <= Convert.ToDecimal(value1));
                    if (checkInfo == null)
                    {
                        logger.Error("检测校验", "checkInfo为空");
                        collectStatus = false;
                        return;
                    }
                    else
                    {
                        if (checkInfo.Result.Equals(1))
                        {
                            testResult.WorkResult = "OK";
                        }
                        else
                        {
                            testResult.WorkResult = "NG";
                        }
                    }
                }
                testResult.LineCode = dataDock.LineCode;
                testResult.StationCode = dataDock.StationCode;
                testResult.ProductId = dataDock.ProductCode;
                testResult.ProductType = dataDock.ProductType;
                testResult.OrderCode = dataDock.OrderCode;
                testResult.ProcessName = operationPointList[i].ItemName;
                testResult.ProcessType = 0;
                testResult.ProcessValue = value1;
                testResult.UnitName = "";
                testResult.MesPushed = 0;
                _testResultService.InsertAsync(testResult);
            }
        }
    }
}